$(function() {
    function loadArticles() {
        $.get("/api/articles", function(data) {
            $("#articleList").empty();
            data.forEach(article => {
                var li = $("<li></li>").text(article.title + " - " + article.content);
                var deleteBtn = $("<button>删除</button>").click(function() {
                    deleteArticle(article._id);
                });
                li.append(deleteBtn);
                $("#articleList").append(li);
            });
        });
    }

    function deleteArticle(articleId) {
        $.ajax({
            url: `/api/articles/${articleId}`,
            method: 'DELETE',
            headers: { 'Authorization': localStorage.getItem('token') },
            success: function() {
                loadArticles();
            }
        });
    }

    $("#publishBtn").click(function() {
        var content = $("#articleContent").val();
        var title = "默认标题"; // 可以根据需要添加标题输入框
        $.post("/api/articles", { title: title, content: content }, function(data) {
            alert('文章发布成功');
            loadArticles();
        }).fail(function() {
            alert('文章发布失败');
        });
    });

    loadArticles();
});
